package com.connectaudio;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.modules.toast.ToastModule;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by JFJ on 2017-11-3.
 */

public class MyNativeModule extends ReactContextBaseJavaModule{

    private Context mContext;
    // 系统的音频文件
    //播放音频文件API
    private MediaPlayer mediaPlayer;
    File mFile = null;
    //当前是否正在播放
    private volatile boolean isPlaying;
    //线程操作
    private ExecutorService mExecutorService = Executors.newSingleThreadExecutor();
    File soundFile;
    MediaRecorder mRecorder;

    public MyNativeModule(ReactApplicationContext reactContext) {
        super(reactContext);
        mContext = reactContext;
    }

    @Override
    public String getName() {
        return "MyNativeModule";
    }

    @ReactMethod
    public void rnCallNativeStartAudio() {
        if (!Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED))
        {
            Toast.makeText(getCurrentActivity(), "SD卡不存在，请插入SD卡！",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        try
        {
            // 创建保存录音的音频文件
            soundFile = new File(Environment
                    .getExternalStorageDirectory().getCanonicalFile()
                    + "/sound.amr");
            Toast.makeText(getCurrentActivity(),"Environment\n" +
                    "                    .getExternalStorageDirectory().getCanonicalFile()", Toast.LENGTH_LONG);
            mRecorder = new MediaRecorder();
            // 设置录音的声音来源
            mRecorder.setAudioSource(MediaRecorder
                    .AudioSource.MIC);
            // 设置录制的声音的输出格式（必须在设置声音编码格式之前设置）
            mRecorder.setOutputFormat(MediaRecorder
                    .OutputFormat.AMR_NB);
            // 设置声音编码的格式
            mRecorder.setAudioEncoder(MediaRecorder
                    .AudioEncoder.AMR_NB);
            mRecorder.setOutputFile(soundFile.getAbsolutePath());
            mRecorder.prepare();
            // 开始录音
            mRecorder.start();  //①
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    @ReactMethod
    public void rnCallNativeStopAudio() {
        if (soundFile != null && soundFile.exists())
        {
            // 停止录音
            mRecorder.stop();  //②
            // 释放资源
            mRecorder.release();  //③
            mRecorder = null;
        }
    }

    @ReactMethod
    public void rnCallNativePlayAudio(){
        try {
            mFile = new File(Environment.getExternalStorageDirectory().getCanonicalFile()+ "/sound.amr");
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (null != mFile && !isPlaying) {
//            isPlaying = true;
            mExecutorService.submit(new Runnable() {
                @Override
                public void run() {
                    startPlay(mFile);
                }
            });
        }
    }

    /**
     * @description 开始播放音频文件
     * @author ldm
     * @time 2017/2/9 16:56
     */
    private void startPlay(File mFile) {
        try {
            //初始化播放器
            mediaPlayer = new MediaPlayer();
            //设置播放音频数据文件
            mediaPlayer.setDataSource(mFile.getAbsolutePath());
            //播放器音量配置
            mediaPlayer.setVolume(1, 1);
            //是否循环播放
            mediaPlayer.setLooping(false);
            //准备及播放
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
